<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="layui/css/layui.css">
    <link rel="stylesheet" href="nprogress/nprogress.css">
    <script src="js/axios.js"></script>
    <script src="layui/layui.js"></script>
    <script src="./nprogress/nprogress.js"></script>
    <script>

        const ERROR_MSG={
            ERR_NETWORK:"网络异常，请检查网络连接",
            ECONNABORTED:"请求超时,请稍后重试"
        };
        const HTTP_MSG={
            401:"未授权",
            404:"访问资源不存在",
            500:"服务器出现异常",
            DEFAULT:"服务器太忙了,你待会再试"
        }
        //请求拦截器
        // 在发送请求之前做些什么
        axios.interceptors.request.use(function(config){
            //config为axios进行异步请求时候，所需要整合后异步请求配置对象

            NProgress.start();//开启进度条
            console.log(config);
            return config;//需要return
        },function(error){
            
            console.log(error);
            console.log("出现问题了");
        });

        //响应拦截器
        //响应成功拦截器的回调函数的参数和axios的then的参数一致
        axios.interceptors.response.use(function(response){
            console.log(response);
            NProgress.done();//关闭进度条
            return response.data;//需要return 返回值
        },function(error){
            console.log(error);
            let msg="";
           if(error.response){//有响应的情况下
                msg= HTTP_MSG[error.response.status];
           }else{
                msg=ERROR_MSG[error.code]
           }
           layer.msg(msg);
        });
        function sendAjax(){
            axios.get("http://127.0.0.1:3000/test/users")
            .then(function(data){
                console.log("---------------")
                console.log(data);
            });
        }
    </script>
</head>
<body>
    <input type="button" value="测试请求响应拦截器" onclick="sendAjax()">
    <input type="button" value="">
</body>
</html>